<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar
      title="一客一价"
      left-arrow
      :border="false"
      fixed
      @click-left="goto()"
    />
    <div class="has-top" />
    <div class="wrapper">
      <!-- <div class="ontitle fs-32">基础信息</div> -->
      <div class="register-form">
        <van-cell-group>
          <van-field
           @click="setUser"
            v-model="model.RealName"
            readonly
            required
            clickable
            label="客户名称"
            placeholder="请选择客户"
          />
      </van-cell-group>
      </div>
      <div class="ontitle fs-32"><div>商品清单</div><div @click="getadd" class="addproduct"><svg-icon icon-class="add" class="fs-26 color3" @goPage="getadd" /><div>添加商品</div></div></div>
      <div class="pd-24 bg-white mb-100" v-if="productList.length > 0">
          <van-checkbox-group v-model="checkedList">
            <div class="flex flex-s-c checkAll" v-if="editState">
              <div class="flex flex-center">
                <p class="checkbox fs-28" :class="checkAllState?'checked':''" @click="checkAll">全选</p>
                <p class="one-del" @click="delProduct">删除</p>
              </div>
              <p class="submitBtn fs-28" @click="editNO">退出编辑</p>
            </div>
            <div class="flex flex-s-c" v-else>
              <div class="flex flex-center">
                <p class="fs-28">共{{productList.length}}件</p>
              </div>
              <p class="submitBtn fs-28" @click="editNO">编辑</p>
            </div>
            <div class="flex product" v-for="(item,index) in productList"  :key="index">
              <div class="w-50 flex pr-25" v-if="editState"><van-checkbox :name="item.ID" checked-color="#F1270C" @click="checkEdit(item)" /></div>
              <div class="flex ptb-30 pr-25">
                <img-box class="is-160 br-10 flex-s-0" :img-url="item.ThumbnailUrl410" />
                <div class="productItem-detail ml-20 flex-1">
                  <p class="text-show-line-2 mb-10 color-dark fs-28">{{ item.ProductName }}</p>
                  <!-- <p class="fs-28 color-gray-light">货号：ZG-NSSB52-1</p> -->
                  <p class="fs-28 color-gray-light">规格：{{item.AttributeNameValue?item.AttributeNameValue:'单规格'}}</p>
                  <p class="mt-10 fs-28">
                    ￥<input class="numinput mr-10" type="number" v-model="item.userPrice">
                  </p>
                </div>
              </div>
            </div>
          </van-checkbox-group>
      </div>
      <div class="bt-button">
        <van-button type="danger" class="bor-ra" size="large" @click="submit">保存</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import SIdentify from 'components/sIdentify'
import amapSelect from 'components/amapSelect'
import areaList from 'utils/area'
import { upLoad } from 'api/upload'
import { getStoreCategoryTreeList } from 'api/storeCategory'
import { storeApply } from 'api/store'
import imgBox from 'components/imgBox'
import { GetWholeSaleListForSku,SaveUserProductByEmployee } from 'api/product'
export default {
  components: {
    SIdentify,
    amapSelect,
    imgBox
  },
  props: {
    clientWidth: {
      type: Number,
      default: document.body.clientWidth
    }
  },
  data() {
    return {
      offerlist:[
				{
					id:1,
					value:'物流配送',
				},
				{
					id:2,
					value:'客户自提',
				},
			],
      radio: 0,
      avar: [],
      advertPictures: [],
      shopPictures: [],
      model: {
      },
			checkedList: [],
      productNameList:[],
      startTime: false,
      endTime: false,
      showArea: false,
      areaList: areaList,
      showAmap: false,
      initAmap: false,
      showBussinessType: false,
      productList:[],
      checkAllState: false,
      productIds:'',
      productIdsArr:[],
      // 请求参数
			requestData: {
				ProductType: 1,
				OrderBy: 'AddTime',
				sort: 'desc',
				PageIndex: 1,
				PageSize: 99
			},
      totalAmout:0,
      editState:false,
      gradeActive:0,
      gradeList:[
        {id:0,name:"8级"},
        {id:1,name:"10级"},
        {id:2,name:"12级"}
      ]
    }
  },
  created() {
   
  },
  mounted() {
    if(localStorage.getItem('customerUser')){
      this.model = JSON.parse(localStorage.getItem('customerUser'));
    }
    if(localStorage.getItem('customerProductList')){
      this.productIdsArr = JSON.parse(localStorage.getItem('customerProductList'));
      this.productIds = JSON.parse(localStorage.getItem('customerProductList')).join(',');
      if( this.productIds.length > 0){
        this.GetWholeSaleListForSku()
      }
    }
  },
  methods: {
    selectGrad(item) {
      this.gradeActive = item.id
      
    },
    changeRadio(index) {
      console.log(index)
      this.radio = index
      this.couponValue = this.offerlist[index].value
      
    },
    //删除
    delProduct(){
      console.log(this.checkedList)
      console.log(this.productNameList)
      this.checkedList.forEach(item => {
        this.productList.forEach((subitem,index) => {
          if(item == subitem.ID){
            this.productList.splice(index, 1);
          }
        })
      })
      this.setEditCheck(false)
      let ids = []
      this.productList.forEach((item,index) => {

        ids.push(item.ID)
      })
      if(this.productList.length==0){
        this.editState = false
      }
      localStorage.setItem('customerProductList', JSON.stringify(ids));
      this.$forceUpdate()
    },
    	// 全选、全不选
      checkAll() {
			this.checkAllState = !this.checkAllState
      this.setEditCheck(this.checkAllState)
      this.$forceUpdate()
    },
		// 设置全选、全不选（编辑）
		setEditCheck(bol) {
      const _this = this
      _this.editIds = ''
			this.checkedList = []
			this.productNameList = []
      if (_this.productList && _this.productList.length > 0) {
        _this.productList.forEach(item => {
          item.check = bol
					if(bol){
						_this.editIds += (item.ID + ',')
						this.checkedList.push(item.ID)
						this.productNameList.push(item.ID)
					}
        })
      }
			console.log(bol,_this.editIds,"是实时")
    },
    checkEdit(item){		
			if(this.productNameList.indexOf(item.ID) === -1){
				this.productNameList.push(item.ID)
			}else{
				this.productNameList.splice(this.productNameList.indexOf(item.ID),1)
			}
      if(this.productNameList.length == this.productList.length){
			  this.checkAllState = true
        this.setEditCheck(true)
      }else{
			  this.checkAllState = false
      }
		}, 
    editNO(){
     this.editState = !this.editState 
    },
    setUser(){
      this.$router.push({
        path: '/customerList' 
      })
    },
    getadd(){
      if(!this.model.RealName){
        this.$toast('请先选择会员')
        return
      }
      this.$router.push({
        path: '/customerProduct' 
      })
    },
    // 获取商品列表
		GetWholeSaleListForSku() {
			// this.requestData.storeId = this.storeId
			const _this = this
			_this.requestData.skuIds = this.productIds
			
			GetWholeSaleListForSku(_this.requestData).then(res => {
				if (res) {
					if (res.Data.Data.length && res.Data.Data.length > 0) {
						_this.totalAmout = res.Data.RecordAmout;
            let productList =  res.Data.Data;
            productList.forEach(item => {
              item.ProductSkuList.forEach(subitem =>{
                subitem.userPrice = subitem.V_GradePrice
                subitem.ProductName = item.ProductName
                subitem.ThumbnailUrl410 = item.ThumbnailUrl410
                if(_this.productIdsArr.indexOf(subitem.ID) != -1){
                  _this.productList.push(subitem)
                }
              })
            })
					}
				}
			})
		},
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identify.identifyCode += this.identify.identifyCodes[this.randomNum(0, this.identify.identifyCodes.length)]
      }
    },
    // 验证码部分end
    // 保存地图详细地址
    confirmAmap(dataModel) {
      // console.log(this.model);
    },
    onConfirm(item) {
      this.model.bussinessType.value = item.text
      this.model.bussinessType.id = item.value
      this.showBussinessType = false
    },

    goto(){
      window.location.href = this.$LocalDomain + '/m/user/StoreManager'
    },
    submit() {
      const self = this
      if(this.editState){
        this.$toast('请先退出编辑再保存')
        return
      }
      if(!this.model.RealName){
        this.$toast('请选择会员')
        return
      }
      if(this.productList.length==0){
        this.$toast('请添加商品')
        return
      }
      let param = {
        UserList:[this.model.UserId]
      }
      let skuList = []
      this.productList.forEach(item => {
        let obj = {
          productId:item.ProductId,
          id:item.ID,
          salePrice:item.V_GradePrice,
          userPrice:+item.userPrice
        }
        skuList.push(obj)
      })

      param.skuList = skuList;
      console.log(param)
      SaveUserProductByEmployee(param).then(res => {
				if (res.Data) {
          this.$toast('保存成功');
          localStorage.removeItem('customerUser')
          localStorage.removeItem('customerProductList')
          setTimeout(e =>{
            this.model = {};
            this.productList = [];
            this.editState = false;
            this.checkedList = [];
            this.productNameList =[];
            this.checkAllState = false;
          },2000)
				}else{
          this.$toast(res.Msg)
        }
			})
    }
  }
}
</script>

<style lang="scss" scoped>
.van-uploader {
  /deep/ .van-uploader__upload,
  /deep/ .van-uploader__preview {
    margin: 0;
  }
}
.advertPictures {
  /deep/ .van-uploader__upload,
  /deep/ .van-uploader__preview {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.wrapper{
  padding:0 24px 24px 24px;
}
.ontitle{
  color: #333;
  font-weight: bold;
  padding: 24px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.addproduct{
  font-size: 24px;
  width: 160px;
  height: 50px;
  line-height: 50px;
  border-radius: 25px;
  border: 2px solid #333333;
  font-weight: normal;
  display: flex;
  justify-content: center;
  align-content: center;
}
.color3{
  color: #333;
  margin-top: 10px;
  margin-right: 3px;
  font-weight: bold;
}
/deep/.van-checkbox{
		margin-bottom: 0 !important;
	}
  [data-theme='blue'] .checked:before {
    background-color: #F1270C!important;
    border-color: #F1270C!important;
  }
	.checkbox{
		padding-left: 50px;
		padding-right: 35px;
		&:before{
			left: 0px;
		}
		&:after{
			left: 12px;
		}
	}
  .one-del{
    width: 120px;
    height: 48px;
    border-radius: 28px;
    border: 1px solid #F1270C;
    font-size: 24px;
    line-height: 48px;
    text-align: center;
  }
  .submitBtn{
    color: #666;
  }
  .numinput{
    width: 196px;
    height: 56px;
    background: #F4F5F6;
    border-radius: 4px;
    border: 1px solid #EBEBEB;
    font-size: 28px;
  }
  .bt-button{
    width: 750px;
    height: 120px;
    background: #FFFFFF;
    box-shadow: 0px -2px 10px 0px rgba(0,0,0,0.1);
    position: fixed;
    left: 0;
    bottom: 0;
  }
  .bor-ra{
    width: 690px;
    height: 90px;
    background: #F1270C;
    border-radius: 44px;
    margin-top: 15px;
    margin-left: 30px;
  }
  .gradeList{
    display: flex;
    &>div{
      width: 90px;
      height: 56px;
      line-height: 56px;
      text-align: center;
      background: #F4F4F4;
      border-radius: 8px;
      margin-right: 12px;
      border: 1px solid #F4F4F4;
    }
    &>div.active{
      background: #FFFFFF;
      color: #F1270C;
      border-color:#F1270C;

    }
  }
</style>
